package main

import (
	"context"
	"flag"
	"fmt"
	logx "gitee.com/wudicaidou/menciis-logx"
	nmap "gitee.com/wudicaidou/menciis-sirecog"
	"github.com/k0kubun/pp"
	"strconv"
	"time"
)

func main() {
	hostStr := flag.String("host", "", "input a single host")
	portStr := flag.String("port", "", "input a single port")
	proto := flag.String("proto", "tcp", "network")
	debug := flag.Bool("debug", false, "set golog level to debug")
	trace := flag.Bool("trace", false, "trace all the socket read and write")
	proxy := flag.String("proxy", "", "set a proxy address(socks5://127.0.0.1:1085)")
	flag.Parse()

	if *hostStr == "" || *portStr == "" {
		fmt.Println("host and port can't be empty")
		return
	}

	if *debug {
		logx.SetLevel("debug")
	}

	config := &nmap.VersionDetectorConfig{
		Proxy:                 *proxy,
		DialTimeout:           10 * time.Second,
		ReadTimeout:           20 * time.Second,
		Rarity:                9,
		Trace:                 *trace,
		ExcludeDangerousPorts: true,
	}

	versionDetector := nmap.NewVersionDetector(config, nmap.GetDefaultProbes())
	versionDetector.SetLogger(logx.Default)
	if len(*proxy) > 0 {
		versionDetector.SetProxy(*proxy)
	}

	var network nmap.TransportProto
	if *proto == "udp" {
		network = nmap.UDP
	} else {
		network = nmap.TCP
	}

	p, err := strconv.Atoi(*portStr)
	if err != nil {
		logx.Error(err)
		return
	}
	version, isOpen, err := versionDetector.Detect(context.Background(), *hostStr, p, network)
	logx.Infof("port is open: %v\n", isOpen)
	if version != nil {
		_, _ = pp.Println(version)
	}
	if err != nil {
		//if strings.Contains(err.Error(), "refused") || strings.Contains(err.Error(), "timeout") {
		//	return
		//}
		logx.Error(err)
		return
	}
}
